﻿using System.Linq;
using System.Web.Mvc;
using GameViewModel;
using KolhozWeb.Models;

namespace KolhozWeb.Controllers
{
    public class HomeController : GameControllerBase
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Что такое Колхоз?.";
            ViewBag.CanBeStarted = TheGame.Options.IsStartAvailable;
            return View(TheGame);
        }

        [HttpGet]
        public ActionResult Setup()
        {
            return View(TheGame.Options);
        }

        public ActionResult Contact()
        {
            return View();
        }

        [HttpPost]
        public JsonResult PersonChecked(string personId, string name, string value)
        {
            var found = TheGame.Options.Persons.FirstOrDefault(p => p.Id.ToString() == personId);
            if (found != null)
                found.IsSelected = bool.Parse(value);
            return new JsonResult { Data = new { Id = personId, Value = value } };
        }

        [HttpPost]
        public JsonResult IsRandomOrderChecked(string value)
        {
            TheGame.Options.IsRandomOrder = bool.Parse(value);
            return new JsonResult { Data = new { Value = value } };
        }

        public ActionResult EditPerson(string personId)
        {
            var found = TheGame.Options.Persons.FirstOrDefault(p => p.Id.ToString() == personId);
            if (found == null)
                return View("Error");

            return View("EditPerson", found);
        }

        public ActionResult CreatePerson()
        {
            return View("EditPerson", new Person("", -1));
        }

        public ActionResult DeletePerson(string personId)
        {
#warning make it work
            var found = TheGame.Options.Persons.FirstOrDefault(p => p.Id.ToString() == personId);
            if (found != null)
            {
                TheGame.Options.Persons.Remove(found);
            }
            return RedirectToAction("Setup");
        }

        [HttpPost]
        public ActionResult SavePerson(string personId, string personName)
        {
            if (string.IsNullOrEmpty(personName))
                return Json(new {error = "Имя не может быть пустым."});

            var found = TheGame.Options.Persons.FirstOrDefault(p => p.Id.ToString() == personId);
            if (found != null && personId != "-1")
                found.Name = personName;
            else
            {
                var person = new Person(personName, TheGame.Options.Persons.Max(p => p.Id) + 1);
                TheGame.Options.Persons.Add(person);
            }
            return Json(new { redirectToUrl = Url.Action("Setup") }); // Return something, but not a view.
        }

    }

}